package com.basker.pisces.springcloud.message.converter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.util.StringUtils;

public class CustomResourceHttpMessageConverter extends ResourceHttpMessageConverter {

    public CustomResourceHttpMessageConverter() {
        super();
    }

    public CustomResourceHttpMessageConverter(boolean supportsReadStreaming) {
        super(supportsReadStreaming);
    }

    @Override
    protected void addDefaultHeaders(HttpHeaders headers, Resource resource, MediaType contentType) throws IOException {
        super.addDefaultHeaders(headers, resource, contentType);

        String fileName = resource.getFilename();
        if (!StringUtils.isEmpty(fileName)) {
            ContentDisposition.Builder disposition = ContentDisposition.builder("attachment");
            disposition.filename(fileName, StandardCharsets.UTF_8);

            headers.setContentDisposition(disposition.build());
        }
    }
}
